package magnus.minimap;

import java.util.ArrayList;

import magnus.minimap.ConnectionManager;

/*
 * Class to manage connection-threads. Two mutable arrays (which stores threads) are used in conjunction to store queued connections and 
 * active connections. The connections won't slow down the UI when threaded. 
 * A maximum of 5 parallell connections are permitted to not clog up the available bandwidth with hundreds of small pictures etc..
 * @Author Magnus Hedlund magnus.hedlund@combitech.se 2010-nov-13  
*/
public class ConnectionManager {	
	private static ConnectionManager myManager;

	public static ConnectionManager getInstance() {
		if (myManager == null) myManager = new ConnectionManager();
		return myManager;
	}
	
	public static final int MAX_CONNECTIONS = 5;
	private ArrayList<Runnable> active = new ArrayList<Runnable>();
	private ArrayList<Runnable> queue = new ArrayList<Runnable>();

	// Send thread into queue and startup new threads if possible. 
	public void add2Queue(Runnable runnable) {
		queue.add(runnable);
		if (active.size() < MAX_CONNECTIONS) startNext();
	}

	// When complete, remove from active list and startup new threads (always possible here).
	public void connectionComplete(Runnable runnable) {
		active.remove(runnable);
		startNext();
	}

	// When activeconns are few enough, create thread to download stuff. Yep!
	private void startNext() {
		if (!queue.isEmpty()) {
			Runnable next = queue.get(0);
			queue.remove(0);
			active.add(next);
			Thread thread = new Thread(next);
			thread.start();
		}
	}
}